import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../models/post_type.dart';
import '../utils/cached_image_widget.dart';

/// 封面选择器
class CoverSelector extends StatelessWidget {
  final String? coverUrl;
  final File? coverFile;
  final Function(File?) onCoverChanged;
  final PostType postType;
  final List<String> imageUrls;

  const CoverSelector({
    super.key,
    this.coverUrl,
    this.coverFile,
    required this.onCoverChanged,
    required this.postType,
    this.imageUrls = const [],
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Text(
                '选择封面',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Color(0xFF333333),
                ),
              ),
              const Spacer(),
              if (coverFile != null || coverUrl != null)
                TextButton(
                  onPressed: () => onCoverChanged(null),
                  child: const Text(
                    '清除',
                    style: TextStyle(
                      color: Color(0xFF999999),
                      fontSize: 14,
                    ),
                  ),
                ),
            ],
          ),
          const SizedBox(height: 12),
          _buildCoverPreview(context),
          const SizedBox(height: 12),
          _buildCoverOptions(context),
        ],
      ),
    );
  }

  Widget _buildCoverPreview(BuildContext context) {
    if (coverFile != null) {
      return Container(
        width: double.infinity,
        height: 200,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          image: DecorationImage(
            image: FileImage(coverFile!),
            fit: BoxFit.cover,
          ),
        ),
      );
    } else if (coverUrl != null) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: CachedImageWidget(
          imageUrl: coverUrl,
          width: double.infinity,
          height: 200,
          fit: BoxFit.cover,
          placeholder: Container(
            width: double.infinity,
            height: 200,
            color: const Color(0xFFF5F5F5),
            child: const Icon(Icons.image, size: 50, color: Colors.grey),
          ),
        ),
      );
    } else {
      return Container(
        width: double.infinity,
        height: 200,
        decoration: BoxDecoration(
          color: const Color(0xFFF5F5F5),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: const Color(0xFFE0E0E0),
            style: BorderStyle.solid,
            width: 1,
          ),
        ),
        child: const Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.add_photo_alternate_outlined,
              size: 48,
              color: Color(0xFF999999),
            ),
            SizedBox(height: 8),
            Text(
              '点击选择封面图片',
              style: TextStyle(
                color: Color(0xFF999999),
                fontSize: 14,
              ),
            ),
          ],
        ),
      );
    }
  }

  Widget _buildCoverOptions(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: _buildOptionButton(
            context,
            icon: Icons.camera_alt_outlined,
            label: '拍照',
            onTap: () => _pickImage(context, ImageSource.camera),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: _buildOptionButton(
            context,
            icon: Icons.photo_library_outlined,
            label: '相册',
            onTap: () => _pickImage(context, ImageSource.gallery),
          ),
        ),
        if (postType == PostType.text && imageUrls.isNotEmpty) ...[
          const SizedBox(width: 12),
          Expanded(
            child: _buildOptionButton(
              context,
              icon: Icons.auto_awesome_outlined,
              label: '自动选择',
              onTap: () => _autoSelectCover(context),
            ),
          ),
        ],
      ],
    );
  }

  Widget _buildOptionButton(
    BuildContext context, {
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
        decoration: BoxDecoration(
          color: const Color(0xFFF8F9FA),
          borderRadius: BorderRadius.circular(8),
          border: Border.all(
            color: const Color(0xFFE0E0E0),
            width: 1,
          ),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              size: 20,
              color: const Color(0xFF007AFF),
            ),
            const SizedBox(width: 8),
            Text(
              label,
              style: const TextStyle(
                color: Color(0xFF007AFF),
                fontSize: 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _pickImage(BuildContext context, ImageSource source) async {
    try {
      final ImagePicker picker = ImagePicker();
      final XFile? image = await picker.pickImage(
        source: source,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );
      
      if (image != null) {
        onCoverChanged(File(image.path));
      }
    } catch (e) {
      if (context.mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择图片失败: $e')),
        );
      }
    }
  }

  void _autoSelectCover(BuildContext context) {
    // 自动选择第一张图片作为封面
    if (imageUrls.isNotEmpty) {
      // 这里可以实现自动选择逻辑
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('已自动选择第一张图片作为封面')),
      );
    }
  }
}

